<template>
	<div class="page">
		<!-- 展示列表模块 -->
		<div class="headerTop" >
			<span >所属项目:</span>
			<el-select v-model="option" placeholder="所属项目" class="inpu">
				<el-option v-for="item in products" :key='item.value' :value="item.value" :label="item.label">
				</el-option>
			</el-select>
			<!-- <el-cascader
				class="inpu"
				v-model="option"
				:options="products"
				clearable
				:props="{ checkStrictly:true,expandTrigger:'hover',emitPath:false}">
			</el-cascader> -->
			设备名称:
			<el-input type="text" v-model="searchKey" class="inpu" placeholder="请输入关键字"></el-input>
			<el-button type="primary" size="small" @click="searchGoods">查询</el-button>
			<el-button type="primary" size="small" @click="showAll" v-if="all && grade==3">刷新全部</el-button>
		</div>
		<div class="header_bottom" v-if="grade<=2">
			<el-button type="success" size="small" @click="add">添加虚拟设备</el-button>
			<el-button type="danger" size="small" @click="deleteMany">批量删除</el-button>
			<!-- <el-button type="primary" size="small" v-if="grade==1" @click="shareEquip">分享设备</el-button> -->
			<el-button type="primary" size="small" @click="showAll" v-if="all">刷新全部</el-button>
		</div>
		<div class="container_table" id="table" >
			<!-- <el-table :data="tabledata" border id="tab" size="mini" row-key="id"
				@selection-change="handleSelectionChange" @row-click="getRow" :header-cell-style="{
				'background-color':tableHead,
				'color': 'white',
                'fontSize':'0.3rem',
				'height':'0.6rem',
				'line-height':'0.6rem',
				'padding':'0.1rem'
			}" :cell-style="{'fontSize':'0.3rem'}"> -->
			    <el-table :data="tabledata" border id="tab"  ref="tab" size="mini" row-key="id"
			    	@selection-change="handleSelectionChange"  :header-cell-style="{
			    	'background-color':tableHead,
			    	'color': 'white',
			        'fontSize':'0.3rem',
			    	'height':'0.6rem',
			    	'line-height':'0.6rem',
			    	'padding':'0.1rem'
			    }" :cell-style="{'fontSize':'0.3rem'}">
				<el-table-column type="selection" min-width="40" reserve-selection fixed>
				</el-table-column>
				<!-- <el-table-column label="ID" prop="id" align="center" min-width="50" fixed>
				</el-table-column> -->
				<el-table-column prop="equip_name" label="名称" align="center" min-width="220" style="position:relative;" fixed>
					<!-- <template slot-scope="scope">
						<span :style="{'color':scope.row.is_alarm?'orangered':''}">{{scope.row.equip_name}}</span><sup
							v-if="scope.row.is_shared" class="shareSup" title="这是别人给你分享的设备">分享</sup>
					</template> -->
				</el-table-column>
				<el-table-column prop="product_name" label="所属项目" align="center" min-width="180">
				</el-table-column>
				<!-- <el-table-column prop="equip_code" label="编码" align="center" min-width="170">
				</el-table-column> -->
				<!-- <el-table-column label="版本" align="center" width="80">
					<template slot-scope="scope">
						<span>{{scope.row.version==2?'V5':'V1'}}</span>
					</template>
				</el-table-column> -->
				<el-table-column label="是否报警" align="center" :min-width="90">
					<template slot-scope="scope">
						<i class="el-icon-bell" :class="scope.row.is_alarm?'alarm_on':'alarm_off'"></i>
						<!-- <span :class="scope.row.is_alarm==1?'yes':'no'" style="transform:translate(-0.1rem,0.1rem)"></span> -->
					</template>
				</el-table-column>
				<el-table-column label="启用状态" align="center" :min-width="50">
					<template slot-scope="scope">
						<el-switch class="mar_l" v-model="scope.row.equip_state" :width="stateWidth"
							@change="sureSetState(scope.row,scope.row.equip_state)" active-color="#13ce66"
							inactive-color="#ccc" active-text="已启用" inactive-text="已禁用" :active-value="one"
							 :inactive-value="zero">
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column v-if="grade<=2"  label="操作" min-width="160" align="center" fixed="right">
					<template slot-scope="scope">
						<el-button type="primary" size="mini" @click="modifyform(scope.row)">编辑</el-button>
						<el-button type="primary" size="mini" @click="goSet(scope.row)">配置</el-button>
						<el-button @click="sureDelete(scope.row)" type="danger" size="mini">删除</el-button>
					</template>
				</el-table-column>
				<!-- <el-table-column v-if="grade<3" label="操作" :min-width="grade<3?160:90" align="center" fixed="right">
					<template slot-scope="scope">
						<el-button type="primary" size="mini" @click="modifyform(scope.row)"
							:disabled="Boolean(scope.row.is_shared)">编辑</el-button>
						<el-dropdown placement="bottom" @command="handleCommand" trigger="click" v-if="grade==1"
							style="margin-left:0.2rem;">
							<span type="primary" style="color:#409eff;cursor: pointer;">
								更多<i class="el-icon-arrow-down el-icon--right"></i>
							</span>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item command="set"
									:disabled="Boolean(nowRow.is_shared)">配置</el-dropdown-item>
								<el-dropdown-item command="copy" :disabled="Boolean(nowRow.is_shared)">复制
								</el-dropdown-item>
								<el-dropdown-item command="delete" :disabled="Boolean(nowRow.is_shared)">删除
								</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</template>
				</el-table-column> -->
			</el-table>
			<div class="pagination">
				<el-pagination style="display:inline-block;vertical-align: middle;margin-top: 0.2rem;"
					@size-change="handleSizeChange" @current-change="current_change" :current-page="queryParams.pageNo"
					:page-size="queryParams.pageSize" :page-sizes="[5,10,15]"
					layout="total, sizes, prev, pager, next, jumper" :total="queryParams.total">
				</el-pagination>
				<!-- <el-button type="priamry" size="small" class="pagebtn" @click="FullScreen">全屏/非全屏切换</el-button> -->
			</div>
        </div>
	</div>
</template>

<script>
        export default {
		name: 'virtualDevice',
		data() {
			return {
				win: window,
				products:[],
				one: 1,
				zero: 0,
				grade: Number(localStorage.getItem("atuser_type")),
				searchKey: '', //输入框内容
				tableHead: localStorage.getItem("bgcolor"),
				option: 0,
				all: false,
				close: false,
				stateWidth: 70,
				nowRow: {
					id: 0,
					equip_name: '',
					equip_code: '',
					type: 3,
					product_id: 0,
					//slaves_count: 1,
					//is_shared: 0,
					//is_sync: 1,
					//is_on: 0,
					//report_interval: 60,
					equip_state: 0,
					version: 0,
				},
				//multipleSelection: [], //搜索的数据传到这里
				queryParams: {
					pageNo: 1,
					pageSize: 10,
					total: 0
				},
				tabledata: [],
				formLabelWidth2: '120px',
				formLabelWidth: '160px'
			}
		},

		created() {
			localStorage.removeItem("virDeviceData");
			this.searchKey = localStorage.getItem('virKeyWord') || '';
			this.option = Number(localStorage.getItem("virOption")) || 0;
			if (this.option || this.searchKey) {
				this.all = true;
			}
			this.queryParams.pageSize = Number(localStorage.getItem("virCurrentSize")) || 10;
			this.queryParams.pageNo = Number(localStorage.getItem("virCurrentNo")) || 1;
			this.getProduct();
			this.showList(this.queryParams.pageNo, this.queryParams.pageSize, this.searchKey, this.option);
		},

        beforeRouteLeave(to, from, next) {
			// 可以访问组件实例 `this`
			//console.log(to.name);
			if (['setVirtualDevice', 'addVirtualDevice', 'editVirtualDevice'].indexOf(to.name) < 0) {
				localStorage.removeItem('virCurrentNo');
				localStorage.removeItem('virCurrentSize');
				localStorage.removeItem('virKeyWord');
				localStorage.removeItem('virOption');
			} else {
				localStorage.setItem("virKeyWord", this.searchKey);
				localStorage.setItem("virOption", this.option);
				localStorage.setItem("virCurrentNo", this.queryParams.pageNo);
				localStorage.setItem("virCurrentSize", this.queryParams.pageSize);
			}
			next();
		},

		methods: {
			current_change: function(currentPage) {
				this.queryParams.pageNo = currentPage;
				this.showList(currentPage, this.queryParams.pageSize, this.searchKey, this.option);
				//console.log(currentPage)
			},

			handleSizeChange(val) {
				this.queryParams.pageSize = val;
				this.showList(this.queryParams.pageNo, val, this.searchKey, this.option);
			},

			getProduct(){
				var that=this;
				this.$http({
					method: 'post',
					url: '/api/product/tree',
					data: {}
				}).then(res => {
					if (res && res.data.result == "success") {
						this.products=res.data.data;
						this.products.unshift({
							value:0,
							label:'全部'
						})
						//console.log(res.data.data);

					}
					//console.log("charu")
				}).catch(error => {

					console.log(error);
				});
			},

		    changeState(row, value) {
				var that = this;
				this.$http({
						method: 'post',
						url: 'api/equip/setState',
						data: {
							'equip_state': value,
							'id': row.id
                        }
					})
					.then(res => {
						if (res && res.data.result == "success") {
							for (let i = 0, len = this.tabledata.length; i < len; i++) {
								if (this.tabledata[i].id == row.id) {
									//如果禁用，要做离线处理；
									this.tabledata[i].is_on = value == 1 ? this.tabledata[i].is_on : 0;
								}
							}
							this.$message({
								message: '恭喜,修改设备状态成功!',
								type: 'success',
								center: true
							});
						}
					}).catch(error => {
						console.log(error);
					});

			},

			sureSetState(row, value) {
				this.$confirm('改变状态将影响到数据的接收与显示, 是否确认此操作?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.changeState(row, value);
				}).catch(() => {
					// this.$message({
					// 	type: 'info',
					// 	message: '已取消改变状态！'
					// });
					this.showList(this.queryParams.pageNo, this.queryParams.pageSize, this.searchKey, this.option);
				});
			},

			goSet(row) {
				//console.log(row);
				localStorage.setItem("virDeviceData", JSON.stringify({
					id: row.id,
					type:3,
					equip_name: row.equip_name,
					equip_code: row.equip_code,
					equip_state: row.equip_state,
					product_id: row.product_id
				}));
				this.$router.push({
					name: 'setVirtualDevice',
					path: '/setVirtualDevice',
					component: 'setVirtualDevice'
				});
			},

			lookData(row) {
				localStorage.setItem("virDeviceData", JSON.stringify({
					id: row.id,
					type: row.type,
					equip_name: row.equip_name,
					equip_code: row.equip_code,
					slaves_count: row.slaves_count,
					is_shared: row.is_shared,
					product_id: row.product_id
				}));
				this.$router.push({
					name: 'screenData',
					path: 'screenData'
				});

			},

			copyDevice(row) {
				this.copyForm.id = row.id;
				this.copyForm.old_name = row.equip_name;
				this.copyForm.equip_name = "";
				this.copyForm.equip_code = "";
				this.copyForm.product_id = row.product_id;
				this.dialogCopyVisible = true;

			},

			sureCopy() {
				if (!this.copyForm.equip_name) {
					this.$message({
						type: 'error',
						message: '设备名称不能为空！'
					})
					return;
				}
				this.$http({
					method: 'post',
					url: 'api/equip/copy',
					data: this.copyForm
				}).then(res => {
					if (res && res.data.result == "success") {
						this.$message({
							type: 'success',
							message: '复制设备成功！'
						});
						this.dialogCopyVisible = false;
						this.showList(this.queryParams.pageNo, this.queryParams.pageSize, this.searchKey, this
							.option);
					} else {
						this.dialogCopyVisible = false;
					}

				}).catch(error => {
					console.log(error);
				});
			},

		    //获取数据函数
			showList: function(num, size, keyword, product_id) {
				var that = this;
				this.$http({
						method: 'post',
						url: 'api/equip/lists',
						data: {
							'limit': size,
							'page': num,
							'type': '3',
							'keyword': keyword,
							'product_id': product_id

						}
					})
					.then(res => {
						if (res && res.data.result == "success") {
							this.tabledata = res.data.data;
							this.queryParams.total = res.data.count;
						}
					}).catch(error => {
						console.log(error)
						this.tabledata = [];
						this.queryParams.total = 0;
						this.queryParams.pageNo = 1;
					});
			},

			// 点击搜索输入框里的内容
			searchGoods() {
				this.all = true;
				this.queryParams.pageNo = 1;
				this.showList(1, this.queryParams.pageSize, this.searchKey, this.option);
				//console.log(this.opid);
			},
			showAll() {
				this.all = false;
				this.queryParams.pageNo = 1;
				this.searchKey = '';
				this.option = 0;
				localStorage.removeItem("virKeyWord");
				localStorage.removeItem("virOption");
				this.showList(1, this.queryParams.pageSize);
			},

			add() {
				this.$router.push({
					name: 'addVirtualDevice',
					path: '/addVirtualDevice'
				})

			},

			deleteMany() {
				if (!this.multipleSelection[0]) {
					this.$message({
						message: "你还没有选中要删除的设备，请先选择！",
						type: 'error',
						center: true
					});
				} else {
					this.$confirm('删除这些设备后,它们将在地图上消失,设备相关数据也将清除,删除后无法恢复,是否确认删除?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.deleteGoods(this.multipleSelection);
					}).catch(() => {
						this.multipleSelection=[];
						this.$refs.tab.clearSelection();
						// this.$message({
						// 	type: 'info',
						// 	message: '已取消删除'
						// });
					});
				}
			},
			deleteGoods(delArr) {
				var that = this;
				let ids = new Array();
				for (let i in delArr) {
					ids.push(delArr[i].id);
				}
				this.$http({
					method: 'post',
					url: 'api/equip/delete',
					data: {
						"id": ids.join(',')

					}
				}).then(res => {
					if (res && res.data.result == "success") {
						this.$message({
							message: '恭喜，数据删除成功!',
							type: 'success',
							center: true
						});
                        this.multipleSelection=[];
                        this.$refs.tab.clearSelection();
						this.showList(this.queryParams.pageNo, this.queryParams.pageSize, this.searchKey, this
							.option);
						setTimeout(function() {
							if (that.tabledata.length == 0 && that.queryParams.pageNo > 1) {
								that.queryParams.pageNo--
								that.showList(that.queryParams.pageNo, that.queryParams.pageSize, that
									.searchKey, that.option);
							}
						}, 1000);

					}
				}).catch(error => {
					console.log(error);
					// alert(error.message)
				});

			},
			//showInfo:function(id){},
			modifyform(row) {
				this.$router.push({
					name: 'editVirtualDevice',
					path: 'editVirtualDevice'
				});
				//localStorage.setItem('editDeviceForm', row);
				localStorage.setItem('editVirDeviceId', row.id);
			},

			// 拿到选中的数据
			handleSelectionChange(val) {
				this.multipleSelection = val;
				//	console.log(val)
			},

			sureDelete(row) {
				this.$confirm('删除后设备将在地图上消失,设备相关数据也将清除,删除后无法恢复,是否确认删除?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.handleClick(row);
				}).catch(() => {
					// this.$message({
					// 	type: 'info',
					// 	message: '已取消删除'
					// });
				});
			},

			handleClick(row) {
				var that = this;
				this.$http({
					method: 'post',
					url: 'api/equip/delete',
					data: {
						"id": row.id

					}
				}).then(res => {
					if (res && res.data.result == "success") {
						this.showList(this.queryParams.pageNo, this.queryParams.pageSize, this.searchKey, this
							.option);
						setTimeout(function() {
							if (that.tabledata.length == 0 && that.queryParams.pageNo > 1) {
								that.queryParams.pageNo--
								that.showList(that.queryParams.pageNo, that.queryParams.pageSize, that
									.searchKey, that.option);
							}
						}, 1000);
					}
				}).catch(error => {
					console.log(error);
				});
			}
		}
	}
</script>

<style scoped>
	.inpu /deep/ .el-input__inner {
		padding-left: 4px;
	}

	.pagination {
		display: block;
		margin: 0 auto;
		width: 80%;
		height: 1rem;
		line-height: 1rem;
	}

	/* 表格 */
	.container_table {
		width: 99.4%;
    margin-top: 0.1rem;
	}

	.marTop {
		margin-top: 0.2rem;
	}

	.inpu {
		display: inline-block;
		width: 5rem;
		height: 0.8rem !important;
		line-height: 0.8rem;
		margin-right: 0.4rem;
	}

	.alarm_off,
	.alarm_on {
		margin-left: -0.1rem;
	}

	.formline,
	.formline_2 {
		height: 0.6rem;
		line-height: 0.6rem;
		width: 54%;
		margin-top: -0.3rem;
		font-size: 0.3rem !important;
		/* border:1px solid red; */
	}

	.formline_2 {
		width: 100%;
		margin-top: 0.2rem
	}

</style>
